//
// Created by francklinson on 2022/1/1 AT 14:06.
//
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <functional>

using namespace std;

class Solution {
public:
    int timeRequiredToBuy(vector<int> &tickets, int k) {
        queue<int> q;
        for (int i = 0; i < tickets.size(); ++i) {
            q.push(i);
        }
        int time = 0;
        while (!q.empty()) {
            int p = q.front();
            q.pop();
            --tickets[p];
            ++time;
            if (p == k && tickets[p] == 0)
                return time;
            if (tickets[p] > 0)
                q.push(p);
        }
        return -1;
    }
};

class Solution2 {
public:
    int timeRequiredToBuy(vector<int> &tickets, int k) {
        int res = 0;
        for (int i = 0; i < tickets.size(); ++i) {
            // 遍历计算每个人所需时间
            if (i <= k) {
                res += min(tickets[i], tickets[k]);
            } else {
                res += min(tickets[i], tickets[k] - 1);
            }
        }
        return res;
    }
};


int main() {
    Solution solution;
    vector<int> tickets{2, 3, 2};
    cout << solution.timeRequiredToBuy(tickets, 2) << endl;
    return 0;
}

